package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: QuickSort
 * @author: chanzhugang
 * @create: 2022/10/18 01:05
 */
public class QuickSort {

    /**
     * 快排
     *
     * @param arr
     * @param n
     */
    public void quickSort(int[] arr, int n) {
        quickSort_(arr, 0, n - 1);
    }

    private void quickSort_(int[] arr, int p, int r) {
        if (p >= r) {
            return;
        }
        // 分区点下标
        int q = partition(arr, p, r);
        quickSort_(arr, p, q - 1);
        quickSort_(arr, q + 1, r);
    }

    private int partition(int[] arr, int p, int r) {
        int i = p - 1;
        int j = p;
        while (j < r) {
            if (arr[j] < arr[r]) {
                swap(arr, i + 1, j);
                i++;
            }
            j++;
        }
        swap(arr, i + 1, r);
        return i + 1;
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
        int[] arr = new int[]{5, 3, 1, 4, 2};
        quickSort.quickSort(arr, arr.length);
        for (int i : arr) {
            System.out.println(i);
        }
    }
}